<template>
  <div ref="box" class="img-box" :style="{width:width+'px', height:height+'px'}" >
    <img ref="picture" :src="imgSrc" alt="" :class="{wider : isWider, narrower : !isWider}">
  </div>
</template>

<script>
export default {
  props: {
    imgSrc: String,
    width: [Number, String],
    height: [Number, String]
  },
  data() {
    return {
      isWider: true
    };
  },
  mounted() {
    let pic = this.$refs.picture;
    let box = this.$refs.box;
    pic.onload = () => {
      let nw = pic.naturalWidth,
        nh = pic.naturalHeight,
        bw = box.offsetWidth,
        bh = box.offsetHeight;
      let n_ratio = nw / nh,
        box_ratio = bw / bh;
      this.isWider = n_ratio > box_ratio ? true : false;
    };
  }
};
</script>

<style lang="less" scoped>
.img-box {
  position: relative;
  overflow: hidden;
  width: 100%;
  img {
    position: absolute;
  }
}
.wider {
  max-width: inherit;
  height: 100%;
  width: auto;
  left: 50%;
  transform: translateX(-50%);
}
.narrower {
  width: 100%;
  height: auto;
  top: 50%;
  transform: translateY(-50%);
}
</style>



